#include "stm32f4xx.h"
#include "Bsp.h"

void SystemClock_Config_HSE_164MHz(void);

int fputc(int ch, FILE *f)
{
    USART_SendData(BSP_USART,  (uint16_t)ch);
    while (USART_GetFlagStatus(BSP_USART, USART_FLAG_TXE) == RESET);
    return ch;
}

void LED_Init()
{
  GPIO_InitTypeDef  GPIO_InitStructure;
  RCC_AHB1PeriphClockCmd(RCC_AHB1Periph_GPIOB, ENABLE);

  GPIO_InitStructure.GPIO_Pin =  GPIO_Pin_2 ;
  GPIO_InitStructure.GPIO_Mode = GPIO_Mode_OUT;
  GPIO_InitStructure.GPIO_OType = GPIO_OType_PP;
  GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
  GPIO_InitStructure.GPIO_PuPd = GPIO_PuPd_NOPULL;

  GPIO_Init(GPIOB, &GPIO_InitStructure);
  GPIO_SetBits(GPIOB, GPIO_Pin_2); // Set the pin to high to turn off the LED
}

void Toggle_GPIO_Pin(GPIO_TypeDef* GPIOx, uint16_t GPIO_Pin)
{
  if (GPIO_ReadOutputDataBit(GPIOx, GPIO_Pin) == Bit_SET)
  {
    GPIO_ResetBits(GPIOx, GPIO_Pin); // Turn off the LED
  }
  else
  {
    GPIO_SetBits(GPIOx, GPIO_Pin); // Turn on the LED
  }
}


int main()
{
  SystemClock_Config_HSE_164MHz();
  LED_Init(); 
  Usart1_DMA_IDLE_Init(); 
  TIM3_Init_500ms();//SYS_RUN_LED
  Button_EXTI0_Init();
    /* Main Loop */
  while (1) 
   {
    if(Usart1_recv_end_flag==1)
    {
        Usart1_recv_end_flag=0;
        Usart1_recv_buff[Usart1_recv_count]=0; //添加结束符
        printf("Recv:%s\r\n",Usart1_recv_buff); //打印接收到的数据
        Usart1_recv_count=0; //清空接收计数器
    }
   }
}

void SystemClock_Config_HSE_164MHz(void)
{
    RCC_DeInit();  // 重置RCC为默认状态
    RCC_HSEConfig(RCC_HSE_ON);  // 开启HSE晶振

    // 等待HSE稳定
    if (RCC_WaitForHSEStartUp() == SUCCESS)
    {
        // 设置电源模块（支持高频）
        RCC_APB1PeriphClockCmd(RCC_APB1Periph_PWR, ENABLE);
        PWR_MainRegulatorModeConfig(PWR_Regulator_Voltage_Scale1);

        // 配置Flash等待周期（延时）——主频越高延时级别越高
        FLASH_SetLatency(FLASH_Latency_5);
        FLASH_PrefetchBufferCmd(ENABLE);
        FLASH_InstructionCacheCmd(ENABLE);
        FLASH_DataCacheCmd(ENABLE);

        // 配置PLL：HSE=8MHz → VCO_IN = 1MHz，VCO_OUT = 328MHz，PLLCLK = 164MHz
        RCC_PLLConfig(RCC_PLLSource_HSE, 8, 328, 2, 7); // M=8, N=328, P=2, Q=7
        RCC_PLLCmd(ENABLE);

        // 等待PLL稳定
        while (RCC_GetFlagStatus(RCC_FLAG_PLLRDY) == RESET);

        // 选择PLL作为系统时钟
        RCC_SYSCLKConfig(RCC_SYSCLKSource_PLLCLK);
        while (RCC_GetSYSCLKSource() != 0x08);

        // 设置AHB, APB1, APB2分频
        RCC_HCLKConfig(RCC_SYSCLK_Div1);    // HCLK = SYSCLK
        RCC_PCLK1Config(RCC_HCLK_Div4);     // APB1 = HCLK / 4
        RCC_PCLK2Config(RCC_HCLK_Div2);     // APB2 = HCLK / 2
    }
    else
    {
        // HSE启动失败：可切回HSI或进入死循环
        while (1);
    }
}
